package com.sgcc.dlsc.monitorredis.util;

import com.sgcc.dlsc.monitorredis.model.bo.Group;
import com.sgcc.dlsc.monitorredis.model.po.NodeInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @Author: 李孟帅
 * @CreateTime: 2019-08-28 10:48
 * @Description: 将需要的节点信息封装进Node实体类
 */
public class InfoToNodeUtil {

    /**
     * @Author 李孟帅
     * @Description 将redis节点info信息封装到Node类中
     * @Date 15:56 2019/9/3
     **/
    public static NodeInfo toNode(Properties info, String server) {
        NodeInfo node = new NodeInfo();
        String[] split = server.split(":");
        node.setTimestamp(DateToUTCUtil.toUTC(new Date()));
        node.setIp(split[0]);
        node.setPort(Integer.parseInt(split[1]));
        node.setRole(info.getProperty("role"));
        node.setMasterHost(info.getProperty("master_host"));
        node.setUsedMemory(Long.parseLong(info.getProperty("used_memory")));
        node.setUsedMemoryHuman(info.getProperty("used_memory_human"));
        node.setUsedCpuSys(Double.parseDouble(info.getProperty("used_cpu_sys")));
        node.setSessions(Integer.parseInt(info.getProperty("connected_clients")));
        node.setKeys(info.getProperty("db0"));
        if (node.getKeys() == null || "".equals(node.getKeys())) {
            node.setKeys("0");
        }
        node.setQPS(Integer.parseInt(info.getProperty("instantaneous_ops_per_sec")));
        return node;
    }

    /**
     * @Author 李孟帅
     * @Description 将redis集群节点进行分组
     * @Date 15:55 2019/9/3
     **/
    public static List<Group> setGroup(List<NodeInfo> nodes) {
        List<Group> groupList = new ArrayList<>();

//        为每一个主节点创建一个组，并将其放在组里
        for (NodeInfo node : nodes) {
            if ("master".equals(node.getRole())) {
//                List<Node> group = new ArrayList<>();
//                group.add(node);
//                groups.put("group" + (++i), group);
                Group group = new Group();
                List<NodeInfo> groupNodes = new ArrayList<>();
                groupNodes.add(node);
                group.setGroup(groupNodes);
                groupList.add(group);
            }
        }
//        判断每一个节点是否为从节点，如果是，就将其放在其所属主节点的组中
        for (NodeInfo node : nodes) {
            if ("slave".equals(node.getRole())) {
                String masterHost = node.getMasterHost();
                b:
                for (int j = 0; j < groupList.size(); j++) {
                    List<NodeInfo> group = groupList.get(j).getGroup();
                    for (NodeInfo childNode : group) {
                        if (masterHost.equals(childNode.getIp())) {
                            group.add(node);
                            break b;
                        }
                    }
                }
            }
        }
        return groupList;
    }
}
